package hrhq.cntvcn.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;

import hrhq.cntvcn.mapper.HrhqContentMapper;
import hrhq.cntvcn.pojo.HrhqContent;
import hrhq.cntvcn.pojo.SearchResult;
import hrhq.cntvcn.service.SearchContentService;
import hrhq.cntvcn.utils.SolrUtils;

@Service
public class SearchContentServiceImpl implements SearchContentService {
	private static Logger logger = Logger.getLogger(SearchContentServiceImpl.class);
	private final static SolrClient solrClient = new SolrUtils().getZkSolrClient();
	

	@Autowired
	private HrhqContentMapper contentMapper;

	

	public void addIndexById(String... ids) {
		logger.info("执行添加索引操作");
		ArrayList<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
		for (String id : ids) {
			HrhqContent content = contentMapper.selectContentById(id);
			SolrInputDocument document = new SolrInputDocument();
			document.addField("id", content.getId());
			document.addField("content_title", content.getTitle());
			document.addField("content_create_date", content.getCreateDate());
			document.addField("content_modify_date", content.getModifyDate());
			document.addField("content_remark", content.getRemark());
			document.addField("content_click_num", content.getClickNum());
			document.addField("content_title_img_path", content.getTitleImgPath());
			document.addField("content_id", content.getContentId());
			docs.add(document);
		}
		
			try {
			solrClient.add(docs);
			solrClient.commit();
			logger.info("add docs success");
		} catch (SolrServerException e) {
			logger.error("Add docs Exception !!!\n" + e.getStackTrace() + "\n" + e.getCause());
			e.printStackTrace();
		} catch (IOException e) {
			logger.error("Unknowned Exception!!!!!\n" + e.getStackTrace() + "\n" + e.getCause());
			e.printStackTrace();
		}

	}

	public void deleteAllIndex() {
		logger.info("执行删除所有索引操作");
		try {
			solrClient.deleteByQuery("*:*");
			solrClient.commit();
			logger.info("删除索引成功");
		} catch (SolrServerException e) {
			logger.error("Delete Indexs Exception !!!\n" + e.getStackTrace() + "\n" + e.getCause());
			e.printStackTrace();
		} catch (IOException e) {
			logger.error("Unknowned Exception!!!!!\n" + e.getStackTrace() + "\n" + e.getCause());
			e.printStackTrace();
		}

	}

	public void deleteIndexByQuery(String query) throws SolrServerException, IOException {
		logger.info("执行删除索引操作");
		solrClient.deleteByQuery(query);
	}

	public SearchResult<HrhqContent> searchByContentTitle(String titleKey, Integer rows, Integer currPage)
			throws SolrServerException {
		logger.info("执行文章标题检索");
		// ApplicationContext context = new
		// ClassPathXmlApplicationContext("classpath:spring/applicationContext-*");
		// long start = System.currentTimeMillis();//测试时间11780ms
		// solrServer =(SolrServer) context.getBean("cloudSolrServer");
		// SearchResult<HrhqContent> searchByKey = searchByKey("_title", titleKey,
		// null,true);
		// long end = System.currentTimeMillis();
		// System.out.println(end-start);
		return searchByKey("content_title", titleKey, null, true, rows, currPage);
	}

	public SearchResult<HrhqContent> searchByContentRemark(String remarkKey, Integer rows, Integer currPage)
			throws SolrServerException {
		logger.info("执行文章摘要检索");
		return searchByKey("content_remark", remarkKey, null, true, rows, currPage);
	}

	public SearchResult<HrhqContent> searchByQuery(String DIYquery, Boolean isHighlight, Integer rows, Integer currPage)
			throws SolrServerException {
		logger.info("执行自定义检索");
		return searchByKey(null, null, DIYquery, isHighlight, rows, currPage);

	}

	public SearchResult<HrhqContent> searchByKey(String searchParam, String keywords, String DIYquery,
			Boolean isHighlight, Integer rows, Integer currPage) throws SolrServerException {
		SolrQuery query = new SolrQuery();
		if (DIYquery != null) {
			query.setQuery(DIYquery);
		} else {
			query.setQuery(searchParam + ":" + keywords);
		}
		query.setStart((currPage - 1) * rows);
		query.setRows(rows);
		if (isHighlight == true) {
			query.setHighlight(true);
			query.addHighlightField(searchParam);
			query.setHighlightSimplePre("<font color=\"red\">");
			query.setHighlightSimplePost("</font>");
		}
		
		QueryResponse queryResponse =null;
		try {
			queryResponse = solrClient.query(query);
		} catch (IOException e) {
			e.printStackTrace();
		}
		SolrDocumentList results = queryResponse.getResults();
		Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
		SearchResult<HrhqContent> searchResult = new SearchResult<HrhqContent>();
		List<HrhqContent> list = new ArrayList<>();
		for (SolrDocument doc : results) {
			HrhqContent content = new HrhqContent();
			// content.setId((String) doc.get("id"));
			if (searchParam.equals("content_title")) {
				content.setTitle(highlighting.get(doc.get("id")).get(searchParam).get(0));
			} else {
				content.setTitle((String) doc.get("_title"));
			}
			// content.setTitle((String) doc.get("_title"));
			content.setCreateDate((Date) doc.get("content_create_date"));
			content.setTag((String) doc.get("content_tag"));
			if (searchParam.equals("content_remark")) {
				content.setRemark(highlighting.get(doc.get("id")).get("searchParam").get(0));
			} else {
				content.setRemark((String) doc.get("content_remark"));
			}
			content.setClickNum((Integer) doc.get("content_click_num"));
			content.setTitleImgPath((String) doc.get("content_title_img_path"));
			content.setContentId((String) doc.get("content_id"));
			// System.out.println(list);
			list.add(content);
		}
		searchResult.setResultList(list);
		searchResult.setRecordCount(results.getNumFound());
		return searchResult;
	}

	/*
	 * 对CloudSolrServer单例注入 private static synchronized SolrServer
	 * getCloudSolrServer(final String zkHost) { if(solrServer == null) { try {
	 * solrServer = new CloudSolrServer(zkHost); }catch(Exception e) { System.out.
	 * println("The URL of zkHost is not correct!! Its form must as below:\n zkHost:port"
	 * ); e.printStackTrace(); } }
	 * 
	 * return solrServer; }
	 */
}
